package org.btik.light.tool;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BioUtil {
    final static char CARRIAGE_RETURN = '\r';
    final static char NEW_LINE = '\n';

    /**
     * 读到下一行
     */
    public static boolean readNewline(InputStream msg) throws IOException {
        int newLineFlag = msg.read();
        // 有/r跳过一个/r
        if (newLineFlag == CARRIAGE_RETURN) {
            newLineFlag = msg.read();
        }
        // 判断是否有新行
        return newLineFlag == NEW_LINE;
    }

    /***
     * @throws IndexOutOfBoundsException 当len小于0
     * */
    public static byte[] read(InputStream msg, int len) throws IOException {
        byte[] result = new byte[len];
        msg.read(result);
        return result;
    }

    /**
     * 读两字节作为无符号数
     */
    public static int readUnsignedShort(InputStream msg) throws IOException {
        int aByte = msg.read();
        int srdByte = msg.read();
        return (aByte << 8) | srdByte;
    }

    /**
     * 读四字节作为无符号数
     */
    public static long readUnsignedInt(InputStream msg) throws IOException {
        return (((long) readUnsignedShort(msg) << 16) | readUnsignedShort(msg));
    }

    /**
     * 读一段字节，直到 util字节出现
     *
     * @param byteArrayList 用于存储变成字节数组
     * @param msg           数据源
     * @param util          分隔符
     */
    public static byte[] readUntil(ByteArrayOutputStream byteArrayList, InputStream msg, byte util) throws IOException {
        int read = msg.read();

        // 最后一行不带换行符，因为作为rpcEnd被截断了
        while (read != util) {
            byteArrayList.write(read);
            read = msg.read();
        }
        if (byteArrayList.size() < 1) {
            return null;
        }
        byte[] line = byteArrayList.toByteArray();
        // 单线程可以重复使用
        byteArrayList.reset();
        return line;
    }
}
